package com.dfd.store.web.servlet;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dfd.store.domain.PageModel;
import com.dfd.store.domain.Product;
import com.dfd.store.service.ProductService;
import com.dfd.store.service.impl.ProductServiceImpl;
import com.dfd.store.utils.CookieUtil;
import com.dfd.store.web.base.BaseServlet;

import net.sf.json.JSONArray;

public class ProductServlet extends BaseServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public String findProductById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 获取页面参数
        String pid = request.getParameter("pid");
        Cookie[] cookies = request.getCookies();
        Cookie cookie = CookieUtil.findCookie(cookies, "history");
        if (cookie == null) {
            Cookie cook = new Cookie("history", pid);
            // response.sendRedirect("product_info.html");
            cook.setMaxAge(60 * 60 * 24 * 7);
            // cook.setPath("/demo1");
            response.addCookie(cook);
        } else {
            String id2 = cookie.getValue();
            cookie.setValue(pid + "#" + id2);
            cookie.setMaxAge(60 * 60 * 24 * 7);
            // cookie.setPath("/demo1");
            response.addCookie(cookie);
        }
        // 调用业务层功能
        ProductService productService = new ProductServiceImpl();
        Product product = productService.findProductById(pid);
        // 将对象放入作用域
        request.setAttribute("product", product);
        request.getSession().setAttribute("sproduct", product);
        return "/jsp/product_info.jsp";

    }

    public String findProductByCidWithPage(HttpServletRequest request, HttpServletResponse respose)
            throws Exception {

        // 获取页数
        String cid = request.getParameter("cid");
        int num = Integer.parseInt(request.getParameter("num"));
        // 调用业务逻辑层
        ProductService productService = new ProductServiceImpl();
        PageModel pm = productService.findProductByCidWithPage(cid, num);
        // 将pageModel放入request中
        request.setAttribute("page", pm);
        return "/jsp/product_list.jsp";
    }

    public void findPbyId(HttpServletRequest request, HttpServletResponse respose) throws Exception {
        String i = request.getParameter("i");
        // 调用业务层功能
        ProductService productService = new ProductServiceImpl();
        Product product = productService.findProductById(i);
        JSONArray jsonArray = JSONArray.fromObject(product);
        respose.setContentType("application/json;charset=utf-8");
        respose.getWriter().print(jsonArray);
    }

}
